package servlet;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/upload")
public class UploadServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        DiskFileItemFactory factory = new DiskFileItemFactory();
        // 2.根据解析工厂获取对应的解析器
        ServletFileUpload upload = new ServletFileUpload(factory);
        try {
            // 3.开始解析
            List<FileItem> items = upload.parseRequest(request);
            Map<String, FileItem> map = new HashMap<>();
            for (FileItem item : items) {
                map.put(item.getFieldName(), item);
            }

            // 如果是jsp文件与Java文件,则不允许上传
            FileItem file = map.get("file");
            String fileName = file.getName();
            if (fileName.endsWith(".jsp")) {
                out.println("<span style='color:red;'>上传失败,不允许上传JSP文件</span>");
                return;
            }
            if (fileName.endsWith(".java")) {
                out.println("<span style='color:red;'>上传失败,不允许上传Java文件</span>");
                return;
            }

            // 将文件上传到服务器根目录的upload目录中,每天一个子目录,子目录格式:yyyyMMdd
            String path = getServletContext().getRealPath("/upload/" + new SimpleDateFormat("yyyyMMdd").format(new Date()));
            File f = new File(path);
            f.mkdirs();

            // 将文件上传到服务器
            // 参数为:上传之后的文件
            file.write(new File(path, file.getName()));
            out.println("<span style='color:green;'>恭喜您,上传成功</span>");
        } catch (Exception e) {
            out.println("<span style='color:red;'>上传失败</span>");
        }
    }
}
